//
//  MeterListViewController.m
//  OST
//
//  Created by mac on 13-7-11.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "MeterListViewController.h"
#import "MeterListCell.h"
#import "CameraViewController.h"
#import "Common.h"
#import "SetData.h"
#import "MeterStatusData.h"
#import "MeterDetailViewController.h"
#import "Utitlity.h"
#import "ChangeInfoDialog.h"
#import "MMProgressHUD.h"

@interface MeterListViewController ()<MeterListCellDelegate,changeDataDicDelegate>
{
    NSString *ipUrl;
    NSTimer *timer;
    NSMutableArray *resultItem;//局域网
    NSMutableArray *tcpResult;
}

@property (assign) MeterDetailViewController *meterDetailVC;

@end

@implementation MeterListViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    closeNextPage = YES;
    threadLoadData = NO;
    
    BottomView *bottomView = [self addBottomView];
    bottomView.btn_camera.hidden = YES;
    dataTableView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - bottomView.frame.size.height);
    self.title =@"Meter";
        
    totalLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
    totalLabel.text = @"Total Power";
    totalLabel.textAlignment = NSTextAlignmentCenter;
    totalLabel.textColor = [UIColor darkGrayColor];
    totalLabel.font = [UIFont boldSystemFontOfSize:18];
    totalLabel.backgroundColor = [UIColor clearColor];
    
    dataTableView.tableHeaderView = totalLabel;
    
    [self refreshData];
    
    self.meterDetailVC = nil;
    timer=[NSTimer scheduledTimerWithTimeInterval:5
                                           target:self
                                         selector:@selector(updateDevStatusChangeWithHttp)
                                         userInfo:nil
                                          repeats:YES];
    
    [self requestGetRoomList];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    self.meterDetailVC = nil;
}

-(CGFloat)rowHeight
{
    return 76;
}

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSUInteger row=[indexPath row];
    static NSString *AutomationCellIdentifier = @"MeterListCellIdentifier";
    MeterListCell *cell = (MeterListCell*)[dataTableView dequeueReusableCellWithIdentifier:AutomationCellIdentifier];
    if (cell==nil)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MeterListCell" owner:self options:nil]lastObject];
        [cell initView];
        cell.delegate= self;
    }
    
    [cell setMCellData:[self.rows objectAtIndex:row]];
    [cell setStatusData:[[self.rows objectAtIndex:row] objectForKey:@"Value"]];
    return cell;
}

-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row=[indexPath row];
   NSDictionary *temdic = [self.rows objectAtIndex:row];
    
    MeterDetailViewController *me = [[MeterDetailViewController alloc]init];
    me.data = temdic;
    NSLog(@"%@",temdic);
    me.title = [temdic objectForKey:@"alias"];
    [self.navigationController pushViewController:me animated:YES];
    self.meterDetailVC = me;
}

-(void)updateTotalValue
{
    float total = 0 ;
    for (MeterListCell *cell in self.rows) {
        total += cell.power;
    }
    totalLabel.text = [NSString stringWithFormat:@"Total Power:%dW",(int)total];
}
/*
-(void)updateStatusData
{
    for (MeterListCell *cell in self.rows) {
        MeterStatusData *meterStatusData = [[MeterStatusData alloc]initWidthZid:[cell.data objectForKey:@"zid"]];
        [meterStatusData getDataWithDataRecivedBlock:^(id data) {
            
            for (NSDictionary *dict in data) {
                NSString *zid = [dict objectForKey:@"zid"];
                //NSString *unit = [dict objectForKey:@"unit"];
                int scale = [[dict objectForKey:@"scale"] intValue];
                //float mvalue = [[dict objectForKey:@"mvalue"] floatValue];
                if (scale == 2) {
                    for (MeterListCell *cell in self.rows) {
                        NSString *xzid = [[cell.data objectForKey:@"zid"] lowercaseString];
                        if ([xzid isEqualToString:zid]) {
                            
                            break;
                        }
                    }
                    [self updateTotalValue];
                    break;
                }
            }
        }];
    }
}
*/

- (void)updateDevStatusChangeWithHttp
{
    ipUrl = [Utitlity judgeipUrl];

    if (ipUrl)
    {
        NSString *updateStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Status.cgi",ipUrl];
        
        [Utitlity commonHTTPMethod:updateStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if ([[responseObject objectForKey:@"state"] isEqualToString:@"Success"])
            {
                NSArray *updateList = [responseObject objectForKey:@"data"];
                
                if (updateList)
                {
                    //                    for (NSDictionary *item in updateList)
                    //                    {
                    //                        NSString *zid = [[item objectForKey:@"ZID"] lowercaseString];
                    //                        NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                    //                        NSInteger meterType = [item getIntegerValForKey:@"MeterType"];
                    //
                    //                        if ( deviceType == 5 && meterType == 1)
                    //                        {
                    //                            for (MeterListCell *cell in self.rows)
                    //                            {
                    //                                NSString *xzid = [[cell.data objectForKey:@"ZID"] lowercaseString];
                    //                                if ([xzid isEqualToString:zid])
                    //                                {
                    //                                    if (self.navigationController.topViewController == self.meterDetailVC)
                    //                                    {
                    //                                        if (self.meterDetailVC.data == cell.data)
                    //                                        {
                    //                                            self.meterDetailVC.data = item;
                    //                                            [self.meterDetailVC loadData];
                    //                                        }
                    //                                    }
                    //                                    [cell setStatusData:item];
                    //                                    cell.labelName.text = [item objectForKey:@"Alias"];
                    //                                    cell.data = item;
                    //                                    cell.delegate = self;
                    //                                    break;
                    //                                }
                    //                            }
                    //                        }
                    //                    }
                    {
                        for (NSDictionary *item in updateList)
                        {
                            NSString *zid = [[item objectForKey:@"ZID"] lowercaseString];
                            NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                            NSInteger meterType = [item getIntegerValForKey:@"MeterType"];
                            
                            if ( deviceType == 5 && meterType == 1)
                            {
                                for (int i = 0;i< [resultItem count];i++)
                                {
                                    NSDictionary *changDic = [resultItem objectAtIndex:i];
                                    NSString *xzid = [[changDic objectForKey:@"ZID"] lowercaseString];
                                    if ([xzid isEqualToString:zid]) {
                                        
                                        if (self.navigationController.topViewController == self.meterDetailVC) {
                                            if (self.meterDetailVC.data == changDic) {
                                                self.meterDetailVC.data = item;
                                                [self.meterDetailVC loadData];
                                            }
                                        }
                                        [resultItem replaceObjectAtIndex:i withObject:item];
                                        break;
                                    }
                                }
                            }
                        }
                        [super doneLoadingTableViewData:resultItem];
                    }
                }
                

            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

- (void)updateDevStatusChangeData:(NSNotification *)data {
    
    ipUrl = [Utitlity judgeipUrl];
    
    if (!ipUrl)
    {
        NSArray *updateList = [data.userInfo objectForKey:NOTIFICATION_USERINFO_UPDATEDATA];
        
        if (updateList)
        {
            for (NSDictionary *item in updateList)
            {
                NSString *zid = [[item objectForKey:@"ZID"] lowercaseString];
                NSInteger deviceType = [item getIntegerValForKey:@"DeviceType"];
                NSInteger meterType = [item getIntegerValForKey:@"MeterType"];
                
                if ( deviceType == 5 && meterType == 1)
                {
                    for (int i = 0;i< [tcpResult count];i++)
                    {
                        NSDictionary *changDic = [tcpResult objectAtIndex:i];
                        NSString *xzid = [[changDic objectForKey:@"ZID"] lowercaseString];
                        if ([xzid isEqualToString:zid]) {
                            
                            if (self.navigationController.topViewController == self.meterDetailVC) {
                                if (self.meterDetailVC.data == changDic) {
                                    self.meterDetailVC.data = item;
                                    [self.meterDetailVC loadData];
                                }
                            }
                            [tcpResult replaceObjectAtIndex:i withObject:item];
//                            [cell setStatusData:item];
//                            cell.labelName.text = [item objectForKey:@"Alias"];
//                            cell.data = item;
//                            cell.delegate = self;
                            break;
                        }
                    }
                }
            }
            [super doneLoadingTableViewData:tcpResult];
        }
    }
}

-(NSArray *)loadPageData:(int)page
{
    [activity startAnimating];
    ipUrl = [Utitlity judgeipUrl];
    
    __block BOOL isLoaded = NO;
    
    if (ipUrl)
    {
        resultItem  = [[NSMutableArray alloc] init];
        NSString *mStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Get.cgi?Get=1",ipUrl];
        [Utitlity commonHTTPMethod:mStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [activity stopAnimating];
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            NSLog(@"responeObject:%@",responseObject);
            
//            NSMutableArray *result = [NSMutableArray array];
            isLoaded = YES;
            if ([responseObject[@"state"] isEqualToString:@"Success"]) {
                NSArray *item = responseObject[@"data"];
                for (int i = 0; i < [item count]; i ++)
                {
                    NSDictionary * dict = [item objectAtIndex:i];
                    NSMutableDictionary *muDict = [dict mutableCopy];
                    NSInteger deviceType = [[dict objectForKey:@"DeviceType"] integerValue];
                    NSInteger meterType = [[dict objectForKey:@"MeterType"] integerValue];
                    if ( deviceType == 5 && meterType == 1) {
                        MeterListCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"MeterListCell" owner:self options:nil]lastObject];
                        [cell initView];
                        NSString *strUuid = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
                        NSString *zidStr = dict[@"ZID"];
                        NSString *appStr = [NSString stringWithFormat:@"%@%@",strUuid,zidStr];
                        [muDict setObject:appStr forKey:@"uuid"];
//                        [cell setMCellData:muDict];
                        cell.delegate = self;
//                        [cell setStatusData:[dict objectForKey:@"Value"]];
                        [resultItem addObject:muDict];
                    }
                }
            }
            [super doneLoadingTableViewData:resultItem];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
            }
    else
    {
        
        [[CMDDataProcessor sharedInstance] getDeviceListResultDataWithDataRecivedBlock:^(id data) {
            
            if (!data || ![data isKindOfClass:[NSDictionary class]]) return;
            
            if ([data[@"state"] isEqualToString:@"Success"])
            {
                [activity stopAnimating];
                tcpResult = [[NSMutableArray alloc] init];
//                NSMutableArray *result = [NSMutableArray array];
                isLoaded = YES;
                {
                    NSArray *devList = data[@"data"];
                    for (int i = 0; i < [devList count]; i ++) {
                        NSDictionary * dict = [devList objectAtIndex:i];
                        NSMutableDictionary *muDict = [dict mutableCopy];
                        NSInteger deviceType = [[muDict objectForKey:@"DeviceType"] integerValue];
                        NSInteger meterType = [[muDict objectForKey:@"MeterType"] integerValue];
                        if ( deviceType == 5 && meterType == 1) {
                            MeterListCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"MeterListCell" owner:self options:nil]lastObject];
                            cell.delegate = self;
                            [cell initView];
                            NSString *strUuid = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
                            NSString *zidStr = dict[@"ZID"];
                            NSString *appStr = [NSString stringWithFormat:@"%@%@",strUuid,zidStr];
                            [muDict setObject:appStr forKey:@"uuid"];
//                            [cell setMCellData:muDict];
//                            [cell setStatusData:[muDict objectForKey:@"Value"]];
                            [tcpResult addObject:muDict];
                        }
                    }
                }
                if ([tcpResult count]>0)
                {
                    [super doneLoadingTableViewData:tcpResult];
                }
                
            }
            //[self updateStatusData];
        }];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!isLoaded) {
            [self loadPageData:1];
        }
    });
    
    /*
     [activity startAnimating];
     [[SetData sharedInstance]getDataWithDataRecivedBlock:^(id data) {
     [activity stopAnimating];
     NSMutableArray *result = [NSMutableArray array];
     for (NSDictionary *dict in data) {
     NSString *kind = [[dict objectForKey:@"kind"] lowercaseString];
     NSString *cmdclass = [[dict objectForKey:@"cmdclass"]lowercaseString];
     if ([kind rangeOfString:@"meter"].length>0 ||[cmdclass rangeOfString:@"meter"].length>0) {
     MeterListCell *cell = [[[NSBundle mainBundle] loadNibNamed:@"MeterListCell" owner:self options:nil]lastObject];
     [cell initView];
     cell.icon.image = [UIImage imageNamed:@"icon_ammeter"];
     cell.labelName.text = [dict objectForKey:@"alias"];
     cell.data = dict;
     [result addObject:cell];
     }
     }
     [super doneLoadingTableViewData:result];
     [self updateStatusData];
     }];
     */
    return nil;
}

-(void)changeMeterInfo:(NSDictionary *)data cell:(MeterListCell*)cell
{
    ChangeInfoDialog  *yijianview = [[[NSBundle mainBundle] loadNibNamed:@"ChangeInfoDialog" owner:self options:nil]lastObject];
    [yijianview initView];
    yijianview.delegate = self;
    [yijianview setRoomDataList:_roomDataList];
    [yijianview setMeterData:data cell:cell];
    [yijianview pageStart];
}

- (void)changeMeterDic:(NSDictionary *)dic
{
    ipUrl = [Utitlity judgeipUrl];
    
//    int i;
//    for (i = 0; i < [tcpResult count];i++)
//    {
//        NSDictionary *proDic = [tcpResult objectAtIndex:i];
//        if([dic[@"ZID"] isEqualToString:proDic[@"ZID"]])
//        {
//            NSMutableDictionary *reDic = [dic mutableCopy];
//            [tcpResult replaceObjectAtIndex:i withObject:reDic];
//        }
//    }
//    [MMProgressHUD showWithStatus:@"修改名字中...."];
//    [MMProgressHUD dismissWithSuccess:@"修改名字成功"];
//    
//    [super doneLoadingTableViewData:tcpResult];
    
    NSLog(@"resultItem:%@",resultItem);
    
    if (ipUrl)
    {
        int i;
        for (i = 0; i < [resultItem count];i++)
        {
            NSDictionary *proDic = [resultItem objectAtIndex:i];
            if([dic[@"ZID"] isEqualToString:proDic[@"ZID"]])
            {
                NSMutableDictionary *reDic = [dic mutableCopy];
                [resultItem replaceObjectAtIndex:i withObject:reDic];
            }
        }
        [MMProgressHUD showWithStatus:@"修改名字中...."];
        [MMProgressHUD dismissWithSuccess:@"修改名字成功"];
        
        [super doneLoadingTableViewData:resultItem];
    }
    else
    {
        [MMProgressHUD showWithTitle:@"修改名称错误" status:@"只能在局域网内进行修改"];
        [MMProgressHUD dismissAfterDelay:1];
    }
}

- (void)changeInfoDialogWithData:(NSDictionary *)dic changeToRoom:(RoomItemModel *)changeRoomData {
    
    for (NSInteger i=0; i<self.rows.count; i++) {
        NSDictionary *data = self.rows[i];
        if ([data[@"ZID"] isEqualToString:dic[@"ZID"]]) {
            
            NSNumber *rooId = dic[@"Room"];
            NSMutableDictionary *reDic = [data mutableCopy];
            reDic[@"Room"] = rooId;
            [self.rows replaceObjectAtIndex:i withObject:reDic];
            [dataTableView reloadData];
            break;
        }
    }
}


@end
